import { defineStore } from 'pinia';
import type { UserType } from '../types';
import { imitateHttp } from '@/utils/index';

const userStore = defineStore('user', {
  state: () => ({
    userInfo: null as UserType | null
  }),
  actions: {
    setUser(user: UserType) {
      this.userInfo = user;
      localStorage.setItem('login_user', JSON.stringify(user));
    },
    registerUser(form: UserType) {
      return imitateHttp((s, f) => {
        form.user_id = parseInt(form.phone.slice(-4));
        localStorage.setItem('regis_user', JSON.stringify(form));
        s('ok');
      })
    },
    login(form: UserType) {
      const regis = localStorage.getItem('regis_user');
      return imitateHttp((s, f) => {
        if (!regis) {
          f('用户未注册');
        }
        else {
          const user: UserType = JSON.parse(regis);
          if (user.phone === form.phone && user.password === form.password) {
            this.setUser(user);
            s('登陆成功');
          }
          else {
            f('手机号或密码错误');
          }
        }
      });
    }
  }
});



export default userStore;
